#!/bin/bash

while getopts "hv" Option
do
 case $Option in
  h ) echo "Usage: `basename $0`"\
       "[-h] [-v] data_file1.mat [data_file2.mat] [data_file.octxt]"
      echo "Convert files from matlab format to octave format."
      echo
      echo "  -h  display this help"
      echo "  -v  verbose mode."
      exit;;
  v ) verbose=1;;
 esac
done
shift $(($OPTIND - 1))


# check verbose
if [ ! ${verbose} ]
 then
  gen_opt="--silent"
else
  gen_opt="--echo-commands"
fi

# define output file name
if [ $# -eq 1 ]
 then
  in_fn=$1
  out_fn=`echo $1 | sed 's/\.mat$/.octxt/'`
else
  in_fn=""
  for ((i=1; i <= $#-1 ; i++))
   do
    eval in_fni=\${$i}
    in_fn="${in_fn}${in_fni} "
  done
  eval out_fn=\${$#}
fi

if [ ${verbose} ]
 then
  echo "Input file(s): ${in_fn}"
  echo "Output file:   ${out_fn}"
fi

# check output
if [ -e ${out_fn} ]
 then
  echo "Error: output file \"${out_fn}\" already exists!"
  exit
fi

# call octave
{ 
  for in_fni in ${in_fn}
   do
    echo load ${in_fni}
  done
  echo save ${out_fn}
} | octave ${gen_opt}

